//
//  MainView.m
//  UCiEnabler
//
//  Created by Delio Brignoli on 21/07/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "UCiEnablerAppDelegate.h"
#import "IEnablerService.h"
#import "MainView.h"

@implementation MainView

@synthesize sectionTitles;
@synthesize statusCell;
@synthesize switchCell;
@synthesize usernameCell;
@synthesize passwordCell;
@synthesize currentOperation;
@synthesize mode;

- (id)initWithFrame:(CGRect)aRect {
	if (self = [super initWithFrame:aRect]) {
		// Initialization code
		currentOperation = nil;
		statusCell = nil;
		usernameCell = nil;
		passwordCell = nil;
		switchCell = nil;
	}
	return self;
}

- (CellLabelWidget *)statusCell {
	if ( statusCell == nil ) {
		statusCell = [[CellLabelWidget alloc] initWithFrame:CGRectZero reuseIdentifier:@"lcell"];
		CellLabelWidget *cell = statusCell;
		cell.nameLabel.text = @"Reachability";
		cell.view = nil; //[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"green.png"]];
	}
	return statusCell;
}

- (CellLabelWidget *)switchCell {
	if ( switchCell == nil ) {
		switchCell = [[CellLabelWidget alloc] initWithFrame:CGRectZero reuseIdentifier:@"lcell"];
		CellLabelWidget *cell = switchCell;
		cell.nameLabel.text = @"Off-campus access";
		cell.view = [[UISwitch alloc] initWithFrame:CGRectZero];
		[((UISwitch *)cell.view) setOn:[[NSUserDefaults standardUserDefaults] boolForKey:AccessStateKey] animated:NO];
		[((UISwitch *)cell.view) addTarget:self action:@selector(toggleSwitch:) forControlEvents:UIControlEventValueChanged];
	}
	return switchCell;	
}

- (CellTextField *)usernameCell {
	if ( usernameCell == nil ) {
		usernameCell = [[CellTextField alloc] initWithFrame:CGRectZero reuseIdentifier:@"tcell"];
		CellTextField *cell = usernameCell;
		UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];
		textField.placeholder = @"Tap here to enter your username";
		textField.borderStyle = UITextBorderStyleNone;
		textField.keyboardType = UIKeyboardTypeASCIICapable;
		textField.autocorrectionType = UITextAutocorrectionTypeNo;
		textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
		textField.returnKeyType = UIReturnKeyNext;
		textField.clearButtonMode = UITextFieldViewModeWhileEditing;    // has a clear 'x' button to the right
		cell.preferenceKey = UserNameKey;
		cell.delegate = self;
		textField.text = [[NSUserDefaults standardUserDefaults] stringForKey:UserNameKey];
		cell.view = textField;
	}
	return usernameCell;	
}

- (CellTextField *)passwordCell {
	if ( passwordCell == nil ) {
		passwordCell = [[CellTextField alloc] initWithFrame:CGRectZero reuseIdentifier:@"tcell"];
		CellTextField *cell = passwordCell;
		UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];
		textField.placeholder = @"Tap here to enter your password";
		textField.borderStyle = UITextBorderStyleNone;
		//textField.keyboardType = UIKeyboardTypeDefault;
		textField.keyboardType = UIKeyboardTypeASCIICapable;
		textField.returnKeyType = UIReturnKeyDone;
		textField.secureTextEntry = YES;
		textField.clearButtonMode = UITextFieldViewModeWhileEditing;    // has a clear 'x' button to the right
		cell.preferenceKey = PasswordKey;
		textField.text = [[NSUserDefaults standardUserDefaults] stringForKey:PasswordKey];
		cell.view = textField;
	}
	return passwordCell;	
}

- (void)setMode:(MainViewMode)targetMode {
	@synchronized(self) {
		if (mode == targetMode) return;

		MainViewMode oldMode = mode;
		mode = targetMode;
		
		if (mode == MainViewUpdating) {
			UITableView *table = (UITableView *)[self viewWithTag:333];

			//[table beginUpdates];
			//rowNum = 2;
			//[table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
			//rowNum = 1;
			//[table deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
			//[table endUpdates];			

			//[UIView beginAnimations:@"delrow" context:NULL];
			//[UIView setAnimationBeginsFromCurrentState:NO];
			//[UIView setAnimationDuration:0.5];
			//self.switchCell.frame = CGRectMake( self.switchCell.frame.origin.x, self.switchCell.frame.origin.y - self.switchCell.frame.size.height, self.switchCell.frame.size.width, self.switchCell.frame.size.height);
			//self.switchCell.alpha = 0.5;
			//[UIView commitAnimations];
			//[table reloadData];
		}

		if (mode != MainViewUpdating) {
			UITableView *table = (UITableView *)[self viewWithTag:333];

			//[table beginUpdates];
			//rowNum = 2;
			//[table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
			//rowNum = 1;
			//[table deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
			//[table endUpdates];

			//[UIView beginAnimations:@"insrow" context:NULL];
			//[UIView setAnimationBeginsFromCurrentState:NO];
			//[UIView setAnimationDuration:0.5];
			//self.switchCell.frame = CGRectMake( self.switchCell.frame.origin.x, self.switchCell.frame.origin.y + self.switchCell.frame.size.height, self.switchCell.frame.size.width, self.switchCell.frame.size.height);
			//self.switchCell.alpha = 1.0;
			//[UIView commitAnimations];
			//[table reloadData];
		}
	}
}

- (void)cellDidEndEditing:(EditableTableViewCell *)cell {
	//This is real bad, we do not implement the right formal protcol 
	//in the interface plus we maybe receiveing messages from other UI components.
	if (cell == self.usernameCell) {
		[self.passwordCell.view becomeFirstResponder];
	}	
}

- (void)drawRect:(CGRect)rect {
	// Drawing code
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return [sectionTitles count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [sectionTitles objectAtIndex:section];
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
	if (section == 1)
		return @"Use the switch to turn off-campus access on or off. Tap on "
					"'Retry' when the service is not reachable or an error "
					"occurred.";
	else
		return @"Tap on the fields above to enter your UC login name and "
					"password.";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (section == 0) {
		return 2;
	}
	if (section == 1) {
		return 2;
	}
	return 0;
}

- (void)toggleSwitch:(id)sender {
	@synchronized(self) {
		UISwitch *sw = (UISwitch *)sender;
		//Store switch state
		[[NSUserDefaults standardUserDefaults] setBool:sw.on forKey:AccessStateKey];
		//Start the update
		UCiEnablerAppDelegate *controller = (UCiEnablerAppDelegate *)[[UIApplication sharedApplication] delegate];
		[controller updateIEnablerServiceAccess];
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
	NSUInteger row = path.row;
	
	if (path.section == 0) {		
		if (row == 0) {
			return self.usernameCell;
		}		
		if (row == 1) {
			return self.passwordCell;
		}
	}
	
	if (path.section == 1) {
		if (row == 0) {
			return self.statusCell;
		}		
		if (row == 1) {
			return self.switchCell;
		}		
	}
	
	return nil;
}

- (void)dealloc {
	[super dealloc];
}


@end
